<?php

namespace app\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Db;
use app\model\Site;
use think\facade\Session;
use think\facade\Request;
use app\utils\Utils;
use app\model\User;
use app\facade\Post;
use Throwable;
use app\utils\DataCache;
use think\helper\Arr;

/**
 * 易混淆词
 * 
 * 社区（整体）
 * └ 帖子（与社区有关系的）
 *   └ 评论（与帖子有关系的）
 *     └ 回复（与评论有关系的）
 */

class Shequ extends BaseController
{
    static public function index($p = 1) // 页面
    {
        $lines = count(Db::connect()->table('site_post')->select()->toArray());
        $posts = Db::connect()->table('site_post')->order(['ison' => 'desc', 'isbest' => 'desc', 'ishot' => 'desc', 'goods' => 'desc', 'time' => 'desc', 'views' => 'desc'])->page(intval($p), 5)->select()->toArray(); // 查询帖子数据
        $result = array();

        foreach ($posts as $key) {
            $user_id = $key['user_id'];
            $userinfo = User::where('id', $user_id)->select()->toArray()[0]; // 查询数据
            $key["user_img"] = $userinfo['img'];
            $key["user_id"] = $user_id;
            $key["user_name"] = $userinfo['name'];
            $result[] = $key;
        }

        $pages = intval($lines / 20);
        if ($lines % 20 != 0) {
            $pages += 1;
        }

        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $user_info = Utils::user($email, $pw);

        return View::fetch(Site::get("template") . '/shequ', [
            'img'  => Site::get("img"),
            'title' => Site::get("title"),
            'about' => Site::get('about'),
            'navitems' => Site::get('navitems'),
            'user_name' => $user_info["name"],
            'user_email' => $user_info["email"],
            'user_img' => $user_info["img"],
            'header' => Site::get("header"),
            'footer' => Site::get("footer"),
            'footer_about' => Site::get("footer_about"),
            'footer_list' => Site::get('footer_list'),
            'post' => $result,
            'lines' => $lines,
            'user_id' => $user_info["id"],
            'pages' => $pages,
            'url' => Site::get("url"),
            'logo' => Site::get("logo")
        ]);
    }

    static public function send_post() // 发送帖子
    {
        $code = 200;
        $value = null;
        $msg = "发送成功";

        $ip = Utils::getIp();

        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        if (Request::isPost()) {
            if ($my_user_info['id'] == '') { //未登录
                $code = 403;
                $msg = '请先登录';
            } else {
                //已登录
                if (Request::post('title') && Request::post('markdown')) {
                    $x = mb_strlen(Request::post('title'));
                    if (intval($x) < 100) {
                        try {
                            $mdtext = Request::post('markdown');
                            $md_original = base64_decode($mdtext);
                            $md_base = $md_original;
                            $md_base = Utils::en_emoji($md_base); //将emoji转换为html
                            $x = mb_strlen($md_base);
                            if ($x < 100000) {
                                if (Post::hasPost(Request::post('title')) || Post::hasSameContentPost($md_base)) {
                                    // 已含有该标题或内容
                                    $code = 406;
                                    $msg = '请勿重复发帖';
                                } else {
                                    // 处理分区数据
                                    $partition_id = Request::post('partition_id', 1); // 兼容旧版API
                                    $partition_ids = Request::post('partition_ids', []); // 新版API：支持多分区

                                    if (empty($partition_ids) && !empty($partition_id)) {
                                        // 兼容旧版API
                                        $partition_ids = [$partition_id];
                                    }

                                    // 验证分区ID的有效性
                                    $valid_partition_ids = [];
                                    if (!empty($partition_ids)) {
                                        // 转换为数组（如果是字符串形式的JSON）
                                        if (is_string($partition_ids)) {
                                            $partition_ids = json_decode($partition_ids, true);
                                        }

                                        // 确保是数组
                                        if (!is_array($partition_ids)) {
                                            $partition_ids = [$partition_ids];
                                        }

                                        foreach ($partition_ids as $id) {
                                            $id = intval($id);
                                            if (Db::table('site_post_partition')->where('id', $id)->find()) {
                                                $valid_partition_ids[] = $id;
                                            }
                                        }
                                    }

                                    if (empty($valid_partition_ids)) {
                                        $code = 401;
                                        $msg = '无效的分区ID';
                                    } else {
                                        // 允许发帖
                                        $img = Request::post('img', '');

                                        $data = [
                                            'user_id' => $my_user_info['id'],
                                            'title' => Request::post('title'),
                                            'text' => $md_base,
                                            'time' => time(),
                                            'ip' => $ip,
                                            'goods' => 0,
                                            'views' => 0,
                                            'likes' => 0,
                                            'ishot' => 0,
                                            'ison' => 0,
                                            'isbest' => 0,
                                            'img' => $img
                                            // 不再包含post_partition字段，通过关联表管理
                                        ];

                                        // 保存帖子
                                        $post_id = Post::SavePost($data);

                                        // 保存分区关系
                                        if ($post_id) {
                                            foreach ($valid_partition_ids as $pid) {
                                                Db::table('site_post_partition_relation')->insert([
                                                    'post_id' => $post_id,
                                                    'partition_id' => $pid
                                                ]);
                                            }
                                            $value = $post_id;
                                        } else {
                                            $code = 500;
                                            $msg = '发布失败';
                                        }
                                    }
                                }
                            } else {
                                $code = 403;
                                $msg = '字数过多';
                            }
                        } catch (Throwable $e) {
                            $code = 401;
                            $msg = '参数有误';
                        }
                    } else {
                        $code = 403;
                        $msg = '字数过多';
                    }
                } else {
                    $code = 401;
                    $msg = '缺少标题或内容';
                }
            }
        }


        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function send_talk() // 发送评论/回复
    {
        $user = Utils::user(Session::get('email'), Session::get('password'));
        if (!$user) {
            return json(['code' => 403, 'msg' => '请先登录']);
        }

        $ip   = Utils::getIp();
        $time = time();
        $text = Utils::en_emoji(Request::post('text', ''));
        if ($text === '') {
            return json(['code' => 401, 'msg' => '缺少内容']);
        }

        /* ---------- 1. 场景路由 ---------- */
        $postId = Request::post('post_id', 0);
        $talkId = Request::post('talk_id', 0);

        /* ---------- 2. 帖子评论 ---------- */
        if ($postId) {
            $post = Post::find($postId);
            if (!$post) {
                return json(['code' => 404, 'msg' => '帖子不存在']);
            }
            if (Db::name('site_talk')->where('post_id', $postId)->where('user_id', $user['id'])->count() >= 15) {
                return json(['code' => 403, 'msg' => '评论数量已满']);
            }
            if (mb_strlen($text) > 200) {
                return json(['code' => 403, 'msg' => '字数过多']);
            }
            $newId = Db::name('site_talk')->insertGetId([
                'user_id' => $user['id'],
                'text' => $text,
                'time' => $time,
                'ip' => $ip,
                'post_id' => $postId
            ]);
            $targetUserId = $post['user_id'];   // 被通知人
            $pushPostId   = $postId;
        }
        /* ---------- 3. 评论回复 ---------- */ elseif ($talkId) {
            $parent = Db::name('site_talk')->find($talkId);
            if (!$parent) {
                return json(['code' => 404, 'msg' => '评论不存在']);
            }
            if (mb_strlen($text) > 150) {
                return json(['code' => 403, 'msg' => '字数过多']);
            }
            $newId = Db::name('site_talk')->insertGetId([
                'user_id' => $user['id'],
                'text' => $text,
                'time' => $time,
                'ip' => $ip,
                'talk_id' => $talkId,
                'post_id' => $parent['post_id']
            ]);
            $targetUserId = $parent['user_id'];
            $pushPostId   = $parent['post_id'];
        } else {
            return json(['code' => 404, 'msg' => '缺少目标']);
        }

        /* ---------- 4. 构造返回 & 通知 ---------- */
        $row = Db::name('site_talk')->find($newId);
        $row['text'] = Utils::html_entity_to_emoji($row['text']);
        $row['img']  = User::where('id', $row['user_id'])->value('img');
        $row['name'] = User::where('id', $row['user_id'])->value('name');

        Utils::send_message(
            $targetUserId,
            $time,
            $user['id'],
            json_encode(['type' => 'talk', 'text' => $text, 'post_id' => $pushPostId])
        );

        return json(['code' => 200, 'msg' => '发送成功', 'data' => $row]);
    }

    static public function get_user($i)
    {
        $data_cache = DataCache::read('shequ_get_user|' . $i);
        if ($data_cache != false) {
            $code = 200;
            $value = null;
            $msg = "获取成功";
            $value = $data_cache;
        } else {
            $user = User::where('id', $i)->select()->toArray(); // 查询用户的数据

            $group = Db::table('site_user_group_user_list')->where('user_id', $i)->select()->toArray();
            // 查询用户组的数据
            $groupItems = array();
            foreach ($group as $item) {
                $groupItem = Db::table('site_user_group')->where('id', $item['group_id'])->select()->toArray();
                $groupItems[] = $groupItem[0]['title'];
            }

            $code = 200;
            $value = null;
            $msg = "获取成功";

            if (count($user) == 0) { // 没有数据
                $code = 404;
                $value = null;
                $msg = "用户不存在";
            } else {
                $code = 200;
                $value = array(
                    'id' => $i,
                    'name' => $user[0]['name'],
                    'img' => $user[0]['img'],
                    'group' => $groupItems
                );
                DataCache::write('shequ_get_user|' . $i, $value, 20);
            }
        }

        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    public static function get_post(int $i)
    {
        /* ---------- 0. 公用变量 ---------- */
        $guest = ['id' => '', 'name' => '未登录', 'img' => ''];
        $user  = Utils::user(Session::get('email'), Session::get('password'));
        $uid   = $user['id'] ?? '';

        /* ---------- 1. 缓存命中 ---------- */
        if ($cache = DataCache::read('shequ_get_post|' . $i)) {
            $cache['views'] += 1;
            $cache['is_goods'] = $uid && Db::name('site_goods')->where(['user_id' => $uid, 'post_id' => $i])->find();

            // 从缓存返回前也要检查权限
            if (!empty($uid)) {
                // 获取用户组相关信息
                $group_tree = Utils::getUserGroupTree($uid);
                $group_ids = self::extractGroupIds($group_tree);
                $visible_post_ids = self::getVisiblePostIdsUsingTree($group_ids);

                // 如果用户没有权限查看该帖子且不是帖子作者，返回403
                if (!in_array($i, $visible_post_ids) && $cache['user_id'] != $uid) {
                    return json(['code' => 403, 'msg' => '没有权限查看该帖子']);
                }
            }

            return json(['code' => 200, 'msg' => '获取成功', 'data' => $cache]);
        }

        /* ---------- 2. 读帖子 ---------- */
        $post = Db::name('site_post')->where(['id' => $i, 'ban' => 0])->find();
        if (!$post) {
            return json(['code' => 404, 'msg' => '帖子不存在']);
        }

        /* ---------- 3. 可见性校验 ---------- */
        if ($post['ban'] == 1 && $post['user_id'] != $uid) {
            return json(['code' => 404, 'msg' => '帖子不存在']);
        }

        /* ---------- 4. 用户权限校验 ---------- */
        if (!empty($uid)) {
            // 获取用户组相关信息
            $group_tree = Utils::getUserGroupTree($uid);
            $group_ids = self::extractGroupIds($group_tree);
            $visible_post_ids = self::getVisiblePostIdsUsingTree($group_ids);

            // 检查用户是否有权限查看该帖子
            // 注意：即使帖子在分区中，也要检查用户是否有权限查看该帖子
            if (!in_array($i, $visible_post_ids) && $post['user_id'] != $uid) {
                return json(['code' => 403, 'msg' => '没有权限查看该帖子']);
            }
        } else {
            // 未登录用户只能查看公开帖子
            // 这里可以根据实际需求调整未登录用户的权限
            return json(['code' => 403, 'msg' => '请登录后查看']);
        }

        /* ---------- 5. 组装数据 ---------- */
        $data = [
            'id'        => $i,
            'title'     => $post['title'],
            'text'      => $post['text'],
            'img'       => $post['img'],
            'user_id'   => $post['user_id'],
            'is_hot'    => $post['ishot'] == 1,
            'is_on'     => $post['ison'] == 1,
            'is_best'   => $post['isbest'] == 1,
            'time'      => $post['time'],
            'views'     => $post['views'] + 1,
            'goods'     => Db::name('site_goods')->where('post_id', $i)->count(),
            'is_goods'  => $uid ? (bool) Db::name('site_goods')->where(['user_id' => $uid, 'post_id' => $i])->find() : false,
        ];

        /* ---------- 6. 写回缓存 + 阅读量 +1 ---------- */
        DataCache::write('shequ_get_post|' . $i, $data, 10);
        Db::name('site_post')->where(['id' => $i, 'ban' => 0])->inc('views')->update();

        return json(['code' => 200, 'msg' => '获取成功', 'data' => $data]);
    }

    public static function get_talk(int $i)
    {
        $user   = Utils::user(Session::get('email'), Session::get('password'));
        $uid    = $user['id'] ?? '';
        $postId = $i;

        $post = Db::name('site_post')->where(['id' => $postId, 'ban' => 0])->find();
        if (!$post) {
            return json(['code' => 404, 'msg' => '帖子不存在']);
        }

        if ($post['ban'] == 1 && $post['user_id'] != $uid) {
            return json(['code' => 404, 'msg' => '帖子不存在']);
        }

        if (!empty($uid)) {
            $group_tree       = Utils::getUserGroupTree($uid);
            $group_ids        = self::extractGroupIds($group_tree);
            $visible_post_ids = self::getVisiblePostIdsUsingTree($group_ids);

            if (!in_array($postId, $visible_post_ids) && $post['user_id'] != $uid) {
                return json(['code' => 403, 'msg' => '没有权限查看该帖子的评论']);
            }
        } else {
            return json(['code' => 403, 'msg' => '请登录后查看']);
        }

        $now = time();
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $now) . ' GMT');
        header('Expires: ' . gmdate('D, d M Y H:i:s', $now + 10) . ' GMT');
        header('Cache-Control: max-age=1');

        $parentTalks = Db::name('site_talk')
            ->where('post_id', $postId)
            ->where('talk_id', 0)          // 父评论
            ->whereOr('talk_id', null)          // 父评论
            ->order('id', 'desc')
            ->select()
            ->toArray();

        if (!$parentTalks) {
            return json(['code' => 200, 'data' => [], 'msg' => '获取成功']);
        }

        $parentIds = array_column($parentTalks, 'id');

        $children = Db::name('site_talk')
            ->where('post_id', $postId)
            ->where('talk_id', 'in', $parentIds)
            ->order('id', 'desc')
            ->select()
            ->toArray();

        $uids  = array_merge(
            array_column($parentTalks, 'user_id'),
            array_column($children, 'user_id')
        );
        $users = Db::name('site_user')
            ->whereIn('id', array_unique($uids))
            ->column('name,img', 'id');

        $childrenMap = [];
        foreach ($children as $r) {
            $childrenMap[$r['talk_id']][] = [
                'id'      => $r['id'],
                'text'    => Utils::html_entity_to_emoji($r['text']),
                'img'     => $users[$r['user_id']]['img'] ?? '',
                'name'    => $users[$r['user_id']]['name'] ?? '',
                'user_id' => $r['user_id'],
                'time'    => $r['time'],
            ];
        }

        $result = [];
        foreach ($parentTalks as $t) {
            $result[] = [
                'id'      => $t['id'],
                'text'    => Utils::html_entity_to_emoji($t['text']),
                'img'     => $users[$t['user_id']]['img'] ?? '',
                'name'    => $users[$t['user_id']]['name'] ?? '',
                'user_id' => $t['user_id'],
                'time'    => $t['time'],
                'talks'   => $childrenMap[$t['id']] ?? [], // 子评论列表
            ];
        }

        return json(['code' => 200, 'data' => $result, 'msg' => '获取成功']);
    }

    static public function post($id) // 帖子页面
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        $posts = Db::connect()->table('site_post')->where('id', $id)->select()->toArray(); // 查询数据

        if (count($posts) == 0) { // 没有数据
            http_response_code(404);
            return View::fetch(Site::get('template') . '/404');
        } else {
            if (intval($posts[0]['user_id']) == intval($my_user_info["id"])) { //如果为登录用户的帖子
                $isme = true;
            } else {
                $isme = false;
            }
            $email = Session::get('email', ''); // 读取用户email

            $post_content = $posts[0]['text'];

            $matches = [];
            $first_image = "";
            if (preg_match_all('/\!\[\]\(.+\)/m', $post_content, $matches)) $first_image = $matches[0][0];

            $first_image = preg_replace('/^!\[(.*?)\]\((.*?) \"(.*?)\"\)$/m', '$2', $first_image); // 图片
            $first_image = preg_replace('/^!\[(.*?)\]\((.*?)\)$/m', '$2', $first_image); // 图片

            $post_plain = Utils::markdownToText($post_content);
            $post_describe = mb_substr($post_plain, 0, 160, 'utf-8');

            View::assign([
                'id' => $id,
                'about' => Site::get('about'),
                'title' => Site::get("title"),
                'site_img'  => Site::get("img"),
                'post_title' => $posts[0]['title'],
                'text' => '', //Utils::markdownToHtml($posts[0]['text']),
                'short_text' => mb_substr($posts[0]['text'], 0, 160, 'utf-8'),
                'navitems' => Site::get('navitems'),
                'my_user_name' => $my_user_info["name"],
                'my_user_email' => $my_user_info["email"],
                'my_user_img' => $my_user_info["img"],
                'my_user_id' => $my_user_info["id"],
                'isme' => $isme,
                'logo' => Site::get("logo"),
                'header' => Site::get("header"),
                'footer' => Site::get("footer"),
                'footer_about' => Site::get("footer_about"),
                'footer_list' => Site::get('footer_list'),

                'post_image' => $first_image,
                'post_plain' => $post_describe
            ]);

            return View::fetch(Site::get('template') . '/post');
        }
    }

    static public function setgoods(int $i)
    {
        /* ---------- 0. 登录检查 ---------- */
        $user = Utils::user(Session::get('email'), Session::get('password'));
        if (!$user['id']) {
            return json(['code' => 403, 'msg' => '请先登录']);
        }

        /* ---------- 1. 参数与帖子存在性 ---------- */
        if ($i <= 0) {
            return json(['code' => 403, 'msg' => '参数有误']);
        }
        $post = Db::name('site_post')->find($i);
        if (!$post) {
            return json(['code' => 404, 'msg' => '帖子不存在']);
        }

        /* ---------- 2. 是否已点赞 ---------- */
        $where = ['user_id' => $user['id'], 'post_id' => $i];
        if (Db::name('site_goods')->where($where)->find()) {
            return json(['code' => 403, 'msg' => '已点赞']);
        }

        /* ---------- 3. 写入点赞 + 实时计数 ---------- */
        Db::name('site_goods')->insert($where);
        $newCnt = Db::name('site_goods')->where('post_id', $i)->count();
        Db::name('site_post')->where('id', $i)->update(['goods' => $newCnt]);

        /* ---------- 4. 通知帖主 ---------- */
        Utils::send_message(
            $post['user_id'],
            time(),
            $user['id'],
            json_encode(['type' => 'good', 'post_id' => $i])
        );

        return json(['code' => 200, 'msg' => '点赞成功', 'data' => $newCnt]);
    }

    public static function unsetgoods(int $i)
    {
        /* --- 0. 登录检查 --- */
        $user = Utils::user(Session::get('email'), Session::get('password'));
        if (!$user['id']) {
            return json(['code' => 403, 'msg' => '请先登录']);
        }

        /* --- 1. 参数校验 --- */
        if ($i <= 0) {
            return json(['code' => 403, 'msg' => '参数有误']);
        }

        /* --- 2. 帖子存在性 --- */
        if (!Db::name('site_post')->find($i)) {
            return json(['code' => 404, 'msg' => '帖子不存在']);
        }

        /* --- 3. 是否点过赞 --- */
        $where = ['user_id' => $user['id'], 'post_id' => $i];
        if (!Db::name('site_goods')->where($where)->find()) {
            return json(['code' => 403, 'msg' => '未点赞']);
        }

        /* --- 4. 删赞 & 实时计数 --- */
        Db::name('site_goods')->where($where)->delete();
        $left = Db::name('site_goods')->where('post_id', $i)->count();
        Db::name('site_post')->where('id', $i)->update(['goods' => $left]);

        return json(['code' => 200, 'msg' => '取消点赞成功', 'data' => $left]);
    }

    static public function sendpost() // 发帖页面
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        return View::fetch(Site::get('template') . '/sendpost', [
            'img' => Site::get('img'),
            'about' => Site::get('about'),
            'title' => Site::get('title'),
            'navitems' => Site::get('navitems'),
            'user_name' => $my_user_info["name"],
            'user_email' => $my_user_info["email"],
            'user_img' => $my_user_info["img"],
            'user_id' => $my_user_info["id"],
            'logo' => Site::get("logo"),
            'about' => Site::get('about'),
            'header' => Site::get("header"),
            'footer' => Site::get("footer"),
            'footer_about' => Site::get("footer_about"),
            'footer_list' => Site::get('footer_list')
        ]);
    }

    /**
     * 从用户组树中提取所有的group_id
     * @param array $group_tree 用户组树
     * @return array 所有group_id的数组
     */
    private static function extractGroupIds($group_tree)
    {
        $group_ids = array();

        if (!is_array($group_tree)) {
            return $group_ids;
        }

        foreach ($group_tree as $group_id => $group_info) {
            $group_ids[] = $group_id;

            // 递归处理子节点
            if (isset($group_info['children']) && !empty($group_info['children'])) {
                $child_ids = self::extractGroupIds($group_info['children']);
                $group_ids = array_merge($group_ids, $child_ids);
            }
        }

        return $group_ids;
    }

    /**
     * 获取用户有权限查看的帖子ID列表
     * @param array $group_ids 用户所属的所有group_id
     * @return array 有权限查看的帖子ID数组
     */
    private static function getVisiblePostIds($group_ids)
    {
        $post_ids = array();

        if (empty($group_ids)) {
            return $post_ids;
        }

        // 查询用户组有权限查看的帖子
        $post_relations = Db::table('site_user_group_partition_post_list')
            ->where('type', 0) // type=0表示帖子
            ->whereIn('group_id', $group_ids)
            ->select()
            ->toArray();

        foreach ($post_relations as $relation) {
            $post_ids[] = $relation['self_id'];
        }

        return array_unique($post_ids);
    }

    /**
     * 获取用户有权限查看的分区ID列表
     * @param array $group_ids 用户所属的所有group_id
     * @return array 有权限查看的分区ID数组
     */
    private static function getVisiblePartitionIds($group_ids)
    {
        $partition_ids = array();

        if (empty($group_ids)) {
            return $partition_ids;
        }

        // 查询用户组有权限查看的分区
        $partition_relations = Db::table('site_user_group_partition_post_list')
            ->where('type', 1) // type=1表示分区
            ->whereIn('group_id', $group_ids)
            ->select()
            ->toArray();

        foreach ($partition_relations as $relation) {
            $partition_ids[] = $relation['self_id'];
        }

        return array_unique($partition_ids);
    }

    /**
     * 使用树状结构获取用户组有权限查看的帖子ID列表
     * @param array $group_ids 用户所属的所有group_id
     * @return array 有权限查看的帖子ID数组
     */
    private static function getVisiblePostIdsUsingTree($group_ids)
    {
        $post_ids = array();

        if (empty($group_ids)) {
            return $post_ids;
        }

        // 先获取所有有权限的分区ID
        $visible_partition_ids = self::getVisiblePartitionIdsUsingTree($group_ids);

        if (!empty($visible_partition_ids)) {
            // 通过关联表查询这些分区下的所有帖子
            $post_relations = Db::table('site_post_partition_relation')
                ->whereIn('partition_id', $visible_partition_ids)
                ->select()
                ->toArray();

            foreach ($post_relations as $relation) {
                $post_ids[] = $relation['post_id'];
            }
        }

        // 再加上直接分配给用户组的帖子权限
        $direct_post_relations = Db::table('site_user_group_partition_post_list')
            ->where('type', 0) // type=0表示帖子
            ->whereIn('group_id', $group_ids)
            ->select()
            ->toArray();

        foreach ($direct_post_relations as $relation) {
            $post_ids[] = $relation['self_id'];
        }

        return array_unique($post_ids);
    }

    /**
     * 使用树状结构获取用户组有权限查看的分区ID列表
     * @param array $group_ids 用户所属的所有group_id
     * @return array 有权限查看的分区ID数组
     */
    private static function getVisiblePartitionIdsUsingTree($group_ids)
    {
        $all_partition_ids = array();
        $visited_partition_ids = array();

        if (empty($group_ids)) {
            return $all_partition_ids;
        }

        // 对每个用户组，获取其分区树
        foreach ($group_ids as $group_id) {
            $partition_tree = Utils::getPartitionTree($group_id);
            if ($partition_tree) {
                // 从分区树中提取所有分区
                $group_partitions = self::extractPartitionsFromTree($partition_tree);

                // 收集分区ID，避免重复
                foreach ($group_partitions as $partition) {
                    $partition_id = $partition['id'];
                    if (!isset($visited_partition_ids[$partition_id])) {
                        $all_partition_ids[] = $partition_id;
                        $visited_partition_ids[$partition_id] = true;
                    }
                }
            }
        }

        return $all_partition_ids;
    }

    static public function get_post_list($p, $i) // 获取帖子列表
    {
        $pagecut = 20;
        header('Content-Type: application/json');

        $code = 200;
        $value = null;
        $msg = "获取成功";

        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $user_info = Utils::user($email, $pw);

        // 检查用户是否已登录
        if (!$user_info || empty($user_info['id'])) {
            // 未登录状态，返回提示帖子
            $system_post = array(
                'id' => 0,
                'title' => '请登录后进入',
                'text' => '您没有权限',
                'user_id' => 0,
                'user_name' => '系统管理员',
                'user_img' => 'https://q1.qlogo.cn/g?b=qq&nk=1942171924&s=100',
                'ison' => 1,
                'isbest' => 0,
                'ishot' => 0,
                'time' => time(),
                'goods' => 0,
                'views' => 0,
                'user_group' => array()
            );

            if ($i == 'all') {
                $value = array("data" => array($system_post), "size" => 1);
            } else {
                // 检查分区是否存在
                if (count(Db::table('site_post_partition')->where('id', intval($i))->select()->toArray()) == 0) {
                    $code = 401;
                    $msg = '不存在该分区';
                } else {
                    $value = array("data" => array($system_post), "size" => 1);
                }
            }
        } else {
            $group_tree = Utils::getUserGroupTree($user_info['id']); // 获取用户组树
            $group_ids = self::extractGroupIds($group_tree); // 提取所有group_id

            $data_cache = DataCache::read('shequ_get_post_list|' . $p . $i . '|' . implode(',', $group_ids));
            if ($data_cache != false) {
                $value = $data_cache;
            } else {
                if ($i == 'all') {
                    // 获取用户有权限查看的帖子ID列表
                    $visible_post_ids = self::getVisiblePostIdsUsingTree($group_ids);

                    if (empty($visible_post_ids)) {
                        // 如果没有任何权限，返回空列表
                        $value = array("data" => array(), "size" => 0);
                    } else {
                        // 查询用户有权限查看的帖子，排除被封禁的帖子
                        $posts = Db::table('site_post')
                            ->whereIn('id', $visible_post_ids)
                            ->where('ban', 0)
                            ->order(['ison' => 'desc', 'isbest' => 'desc', 'ishot' => 'desc', 'time' => 'desc', 'goods' => 'desc',  'views' => 'desc'])
                            ->page(intval($p), $pagecut)
                            ->select()
                            ->toArray(); // 查询帖子数据

                        $result = array();

                        foreach ($posts as $key) {
                            $user_id = $key['user_id'];
                            $userinfo = User::where('id', $user_id)->select()->toArray()[0]; // 查询数据
                            $key["user_img"] = $userinfo['img'];
                            $key["user_id"] = $user_id;
                            $key["user_name"] = $userinfo['name'];
                            $key['text'] = mb_strlen($key['text']) > 100 ? (mb_substr($key['text'], 0, 100, "utf-8") . "...") : $key['text'];
                            unset($key['ip']);

                            // 获取帖子的分区信息
                            $post_partitions = Db::table('site_post_partition_relation')
                                ->alias('r')
                                ->join('site_post_partition p', 'r.partition_id = p.id')
                                ->where('r.post_id', $key['id'])
                                ->field('p.id, p.name')
                                ->select()
                                ->toArray();

                            $partition_ids = array();
                            $partition_names = array();
                            foreach ($post_partitions as $partition) {
                                $partition_ids[] = $partition['id'];
                                $partition_names[] = $partition['name'];
                            }

                            $key['partition_ids'] = $partition_ids;
                            $key['partition_names'] = $partition_names;

                            // 获取用户组信息
                            $groups = Db::table('site_user_group_user_list')->where('user_id', $user_id)->select()->toArray();
                            $key['user_group'] = array();
                            if (count($groups) > 0) {
                                foreach ($groups as $m) {
                                    $key['user_group'][] = Db::table('site_user_group')->where('id', $m['group_id'])->select()->toArray()[0]['title'];
                                }
                            }

                            $result[] = $key;
                        }

                        $pages = count(Db::table('site_post')->whereIn('id', $visible_post_ids)->select()->toArray());
                        if ($pages % $pagecut == 0) {
                            $pages = $pages / $pagecut;
                        } else {
                            $pages = ceil($pages / $pagecut);
                        }

                        $value = array("data" => $result, "size" => $pages);
                    }
                } else {
                    // 检查分区是否存在
                    if (count(Db::table('site_post_partition')->where('id', intval($i))->select()->toArray()) == 0) {
                        $code = 401;
                        $msg = '不存在该分区';
                    } else {
                        // 检查用户是否有权限查看该分区
                        $visible_partition_ids = self::getVisiblePartitionIdsUsingTree($group_ids);

                        if (!empty($visible_partition_ids) && !in_array(intval($i), $visible_partition_ids)) {
                            // 用户没有权限查看该分区
                            $code = 403;
                            $msg = '没有权限查看该分区';
                        } else {
                            // 通过关联表查询该分区下的帖子，排除被封禁的帖子
                            $posts = Db::connect()->table('site_post')
                                ->alias('p')
                                ->join('site_post_partition_relation r', 'p.id = r.post_id')
                                ->where('r.partition_id', intval($i))
                                ->where('p.ban', 0)
                                ->order(['ison' => 'desc', 'isbest' => 'desc', 'ishot' => 'desc', 'time' => 'desc', 'goods' => 'desc',  'views' => 'desc'])
                                ->page(intval($p), $pagecut)
                                ->select()
                                ->toArray(); // 查询帖子数据

                            $result = array();

                            foreach ($posts as $key) {
                                $user_id = $key['user_id'];
                                $userinfo = User::where('id', $user_id)->select()->toArray()[0]; // 查询数据
                                $key["user_img"] = $userinfo['img'];
                                $key["user_id"] = $user_id;
                                $key["user_name"] = $userinfo['name'];
                                $key['text'] = mb_strlen($key['text']) > 100 ? (mb_substr($key['text'], 0, 100, "utf-8") . "...") : $key['text'];
                                unset($key['ip']);

                                // 获取帖子的分区信息
                                $post_partitions = Db::table('site_post_partition_relation')
                                    ->alias('r')
                                    ->join('site_post_partition p', 'r.partition_id = p.id')
                                    ->where('r.post_id', $key['id'])
                                    ->field('p.id, p.name')
                                    ->select()
                                    ->toArray();

                                $partition_ids = array();
                                $partition_names = array();
                                foreach ($post_partitions as $partition) {
                                    $partition_ids[] = $partition['id'];
                                    $partition_names[] = $partition['name'];
                                }

                                $key['partition_ids'] = $partition_ids;
                                $key['partition_names'] = $partition_names;

                                // 获取用户组信息
                                $groups = Db::table('site_user_group_user_list')->where('user_id', $user_id)->select()->toArray();
                                $key['user_group'] = array();
                                if (count($groups) > 0) {
                                    foreach ($groups as $m) {
                                        $key['user_group'][] = Db::table('site_user_group')->where('id', $m['group_id'])->select()->toArray()[0]['title'];
                                    }
                                }

                                $result[] = $key;
                            }

                            $pages = count(Db::connect()->table('site_post')
                                ->alias('p')
                                ->join('site_post_partition_relation r', 'p.id = r.post_id')
                                ->where('r.partition_id', intval($i))
                                ->where('p.ban', 0)
                                ->select()->toArray());
                            if ($pages % $pagecut == 0) {
                                $pages = $pages / $pagecut;
                            } else {
                                $pages = ceil($pages / $pagecut);
                            }

                            $value = array("data" => $result, "size" => $pages);
                            DataCache::write('shequ_get_post_list|' . $p . $i . '|' . implode(',', $group_ids), $value, 10);
                        }
                    }
                }
            }
        }

        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function get_post_partition() // 获取帖子分区
    {
        header('Content-Type: application/json');

        $code = 200;
        $msg = "获取成功";
        $data = null;

        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $user_info = Utils::user($email, $pw);

        // 检查用户是否已登录
        if (!$user_info || empty($user_info['id'])) {
            // 未登录状态，返回空的分区列表
            $data = array();
        } else {
            // 调试信息：用户信息
            //print_r('用户ID: ' . $user_info['id'] );

            // 获取用户组相关信息
            $group_tree = Utils::getUserGroupTree($user_info['id']); // 获取用户组树

            // 调试信息：用户组树
            //print_r('用户组树结构: ' . json_encode($group_tree, JSON_UNESCAPED_UNICODE));

            $group_ids = self::extractGroupIds($group_tree); // 提取所有group_id

            // 调试信息：提取的用户组ID列表
            //print_r('提取的用户组ID列表: ' . json_encode($group_ids));

            if (empty($group_ids)) {
                // 如果用户不属于任何组，返回空列表
                $data = array();
                //print_r('用户不属于任何组');
            } else {
                $all_partition_trees = array();
                $visited_partition_ids = array();

                // 对每个用户组，获取其分区树
                foreach ($group_ids as $group_id) {
                    //print_r('处理用户组ID: ' . $group_id);
                    $partition_tree = Utils::getPartitionTree($group_id);

                    // 调试信息：每个组的分区树
                    //print_r('用户组 ' . $group_id . ' 的分区树: ' . json_encode($partition_tree, JSON_UNESCAPED_UNICODE));

                    if ($partition_tree) {
                        // 合并分区树，避免重复
                        $all_partition_trees = self::mergePartitionTrees($all_partition_trees, $partition_tree, $visited_partition_ids);
                    } else {
                        //print_r('用户组 ' . $group_id . ' 没有可访问的分区');
                    }
                }

                // 调试信息：最终的分区树
                //print_r('最终返回的分区树: ' . json_encode($all_partition_trees, JSON_UNESCAPED_UNICODE));

                $data = $all_partition_trees;
            }
        }

        return Utils::api_response($code, $msg, $data);
    }

    /**
     * 从分区树中提取所有分区
     * @param array $tree 分区树状结构
     * @return array 所有分区信息的扁平化数组
     */
    private static function extractPartitionsFromTree($tree)
    {
        $partitions = array();

        foreach ($tree as $partition_id => $partition_info) {
            // 移除children字段，避免递归时的深度问题
            $partition_without_children = $partition_info;
            if (isset($partition_without_children['children'])) {
                unset($partition_without_children['children']);
            }

            $partitions[] = $partition_without_children;

            // 递归处理子分区
            if (isset($partition_info['children']) && !empty($partition_info['children'])) {
                $child_partitions = self::extractPartitionsFromTree($partition_info['children']);
                $partitions = array_merge($partitions, $child_partitions);
            }
        }

        return $partitions;
    }

    /**
     * 合并多个分区树，避免重复
     * @param array $target_tree 目标分区树
     * @param array $source_tree 源分区树
     * @param array &$visited_partition_ids 已访问的分区ID数组
     * @return array 合并后的分区树
     */
    private static function mergePartitionTrees($target_tree, $source_tree, &$visited_partition_ids)
    {
        if (!is_array($source_tree) || empty($source_tree)) {
            return $target_tree;
        }

        foreach ($source_tree as $partition_id => $partition_info) {
            // 如果分区ID是数字键，则需要特殊处理
            if (is_numeric($partition_id) && isset($partition_info['id'])) {
                $actual_id = $partition_info['id'];

                if (!isset($visited_partition_ids[$actual_id])) {
                    // 深拷贝分区信息，避免引用问题
                    $new_partition = $partition_info;

                    // 递归合并子分区
                    if (isset($partition_info['children']) && !empty($partition_info['children'])) {
                        $new_partition['children'] = array();
                        if (isset($target_tree[$actual_id]) && isset($target_tree[$actual_id]['children'])) {
                            $new_partition['children'] = $target_tree[$actual_id]['children'];
                        }
                        $new_partition['children'] = self::mergePartitionTrees($new_partition['children'], $partition_info['children'], $visited_partition_ids);
                    }

                    $target_tree[$actual_id] = $new_partition;
                    $visited_partition_ids[$actual_id] = true;
                } else if (isset($partition_info['children']) && !empty($partition_info['children'])) {
                    // 已经存在的分区，递归合并其子分区
                    if (!isset($target_tree[$actual_id]['children'])) {
                        $target_tree[$actual_id]['children'] = array();
                    }
                    $target_tree[$actual_id]['children'] = self::mergePartitionTrees($target_tree[$actual_id]['children'], $partition_info['children'], $visited_partition_ids);
                }
            } else {
                // 处理关联数组形式的树
                if (!isset($visited_partition_ids[$partition_id])) {
                    // 深拷贝分区信息，避免引用问题
                    $new_partition = $partition_info;

                    // 递归合并子分区
                    if (isset($partition_info['children']) && !empty($partition_info['children'])) {
                        $new_partition['children'] = array();
                        if (isset($target_tree[$partition_id]) && isset($target_tree[$partition_id]['children'])) {
                            $new_partition['children'] = $target_tree[$partition_id]['children'];
                        }
                        $new_partition['children'] = self::mergePartitionTrees($new_partition['children'], $partition_info['children'], $visited_partition_ids);
                    }

                    $target_tree[$partition_id] = $new_partition;
                    $visited_partition_ids[$partition_id] = true;
                } else if (isset($partition_info['children']) && !empty($partition_info['children'])) {
                    // 已经存在的分区，递归合并其子分区
                    if (!isset($target_tree[$partition_id]['children'])) {
                        $target_tree[$partition_id]['children'] = array();
                    }
                    $target_tree[$partition_id]['children'] = self::mergePartitionTrees($target_tree[$partition_id]['children'], $partition_info['children'], $visited_partition_ids);
                }
            }
        }

        return $target_tree;
    }

    static public function get_home_post_list() // 获取首页的帖子列表
    {
        header('Content-Type: application/json');

        $code = 200;
        $value = null;
        $msg = "获取成功";

        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $user_info = Utils::user($email, $pw);

        // 检查用户是否已登录
        if (!$user_info || empty($user_info['id'])) {
            // 未登录状态，返回提示帖子
            $system_post = array(
                'id' => 0,
                'title' => '请登录后进入',
                'text' => '您没有权限',
                'user_id' => 0,
                'user_name' => '系统管理员',
                'user_img' => 'https://q1.qlogo.cn/g?b=qq&nk=1942171924&s=100',
                'ison' => 1,
                'isbest' => 0,
                'ishot' => 0,
                'time' => time(),
                'goods' => 0,
                'views' => 0
            );
            $value = array($system_post);
        } else {
            // 获取用户组相关信息
            $group_tree = Utils::getUserGroupTree($user_info['id']); // 获取用户组树
            $group_ids = self::extractGroupIds($group_tree); // 提取所有group_id

            // 获取用户有权限查看的帖子ID列表 - 使用与get_post_list相同的权限检查逻辑
            $visible_post_ids = self::getVisiblePostIdsUsingTree($group_ids);

            $posts = array();
            if (empty($visible_post_ids)) {
                // 如果没有任何权限，返回空列表
                $posts = array();
            } else {
                // 查询用户有权限查看的前3条帖子，排除被封禁的帖子
                $posts = Db::table('site_post')
                    ->whereIn('id', $visible_post_ids)
                    ->where('ban', 0)
                    ->order(['ison' => 'desc', 'isbest' => 'desc', 'ishot' => 'desc', 'time' => 'desc', 'goods' => 'desc', 'views' => 'desc'])
                    ->page(1, 3)
                    ->select()
                    ->toArray(); // 查询帖子数据
            }

            $result = array();

            foreach ($posts as $key) {
                $user_id = $key['user_id'];
                $userinfo = User::where('id', $user_id)->select()->toArray()[0]; // 查询数据
                $key["user_img"] = $userinfo['img'];
                $key["user_id"] = $user_id;
                $key["user_name"] = $userinfo['name'];
                $key['text'] = mb_strlen($key['text']) > 100 ? (mb_substr($key['text'], 0, 100, "utf-8") . "...") : $key['text'];
                unset($key['ip']);

                // 获取帖子的分区信息
                $post_partitions = Db::table('site_post_partition_relation')
                    ->alias('r')
                    ->join('site_post_partition p', 'r.partition_id = p.id')
                    ->where('r.post_id', $key['id'])
                    ->field('p.id, p.name')
                    ->select()
                    ->toArray();

                $partition_ids = array();
                $partition_names = array();
                foreach ($post_partitions as $partition) {
                    $partition_ids[] = $partition['id'];
                    $partition_names[] = $partition['name'];
                }

                $key['partition_ids'] = $partition_ids;
                $key['partition_names'] = $partition_names;

                $result[] = $key;
            }

            $value = $result;
        }

        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function del_post()
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        $post_id = Request::post("post_id", false);

        if ($my_user_info['id'] == '') {
            //未登录
            return json(array('code' => 403, 'msg' => '未登录'));
        }

        if (!$post_id) {
        } else {
            $posts = Db::table('site_post')->where('id', $post_id)->select()->toArray(); // 查询帖子的数据
            if (count($posts) == 0) { // 不存在
                return json(array('code' => 404, 'msg' => '删除失败'));
            } else {
                if (intval($posts[0]['user_id']) == intval($my_user_info['id'])) {
                    Db::table('site_post')->where('id', $post_id)->delete();
                    return json(array('code' => 200, 'msg' => '删除成功'));
                } else {
                    return json(array('code' => 403, 'msg' => '删除失败'));
                }
            }
        }
    }

    static public function search_post($p = 1)
    {
        //搜索帖子
        $pagecut = 20;
        header('Content-Type: application/json');

        $code = 200;
        $value = null;
        $msg = "获取成功";
        $key_word = Request::get("key_word", false);
        if (!$key_word) {
            //缺少关键词
            return json(array("code" => 400, 'msg' => '参数有误'));
        }
        $posts = Db::table('site_post')->where('title|text', 'LIKE', '%' . $key_word . '%')->order(['ison' => 'desc', 'isbest' => 'desc', 'ishot' => 'desc', 'time' => 'desc', 'goods' => 'desc',  'views' => 'desc'])->page(intval($p), $pagecut)->select()->toArray(); // 查询帖子数据
        $result = array();

        foreach ($posts as $key) {
            $user_id = $key['user_id'];
            $userinfo = Db::table('site_user')->where('id', $user_id)->select()->toArray()[0]; // 查询数据
            $key["user_img"] = $userinfo['img'];
            $key["user_id"] = $user_id;
            $key["user_name"] = $userinfo['name'];
            $key['text'] = mb_strlen($key['text']) > 100 ? (mb_substr($key['text'], 0, 100, "utf-8") . "...") : $key['text'];
            unset($key['ip']);
            $result[] = $key;
        }

        $pages = count(Db::table('site_post')->where('title|text', 'LIKE', '%' . $key_word . '%')->select()->toArray());
        if ($pages % $pagecut == 0) {
            $pages = $pages / $pagecut;
        } else {
            $pages = ceil($pages / $pagecut);
        }

        $value = array("data" => $result, "size" => $pages);


        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function change_post($p)
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);
        $post_id = $p;

        if ($my_user_info['id'] == '') {
            //未登录
            return View::fetch(Site::get('template') . '/404');
        } else {
            //登录鉴权完毕
            $posts = Db::table('site_post')->where('id', $post_id)->select()->toArray(); // 查询帖子的数据
            if (count($posts) == 0) { // 不存在
                return View::fetch(Site::get('template') . '/404');
            } else {
                if (intval($posts[0]['user_id']) == intval($my_user_info['id'])) {
                    //权限鉴定完成
                    return View::fetch(Site::get('template') . '/changepost', [
                        'img' => Site::get('img'),
                        'about' => Site::get('about'),
                        'title' => Site::get('title'),
                        'logo' => Site::get('logo'),
                        'navitems' => Site::get('navitems'),
                        'user_name' => $my_user_info["name"],
                        'user_email' => $my_user_info["email"],
                        'user_img' => $my_user_info["img"],
                        'user_id' => $my_user_info["id"],
                        'about' => Site::get('about'),
                        'header' => Site::get("header"),
                        'footer' => Site::get("footer"),
                        'footer_about' => Site::get("footer_about"),
                        'footer_list' => Site::get('footer_list')
                    ]);
                } else {
                    //无权限
                    return View::fetch(Site::get('template') . '/404');
                }
            }
        }
    }

    static public function change_post_api()
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);
        $post_id = Request::post('post_id', false);

        if ($my_user_info['id'] == '') {
            //未登录
            return json(array('code' => 403, 'msg' => '参数有误'));
        } else {
            //登录鉴权完毕
            $posts = Db::table('site_post')->where('id', $post_id)->select()->toArray(); // 查询帖子的数据
            if (count($posts) == 0) { // 不存在
                return json(array('code' => 404, 'msg' => '帖子不存在'));
            } else {
                if (intval($posts[0]['user_id']) == intval($my_user_info['id'])) {
                    //权限鉴定完成
                    $title = Request::post('title', false);
                    $markdown = Request::post('markdown', false);
                    $partition_id = Request::post('partition_id', 1); // 兼容旧版API
                    $partition_ids = Request::post('partition_ids', []); // 新版API：支持多分区

                    if (!$title || !$markdown || !$post_id) { //缺少参数
                        return json(array('code' => 404, 'msg' => '参数有误'));
                    } else {
                        //参数完整
                        $x = mb_strlen($title);
                        if (intval($x) < 100) {
                            //字数符合要求
                            try {
                                $mdtext = $markdown;
                                $md_original = base64_decode($mdtext);
                                $md_base = $md_original;
                                $x = mb_strlen($md_base);
                                if ($x < 100000) {
                                    // 处理分区数据
                                    if (empty($partition_ids) && !empty($partition_id)) {
                                        // 兼容旧版API
                                        $partition_ids = [$partition_id];
                                    }

                                    // 验证分区ID的有效性
                                    $valid_partition_ids = [];
                                    if (!empty($partition_ids)) {
                                        // 转换为数组（如果是字符串形式的JSON）
                                        if (is_string($partition_ids)) {
                                            $partition_ids = json_decode($partition_ids, true);
                                        }

                                        // 确保是数组
                                        if (!is_array($partition_ids)) {
                                            $partition_ids = [$partition_ids];
                                        }

                                        foreach ($partition_ids as $id) {
                                            $id = intval($id);
                                            if (Db::table('site_post_partition')->where('id', $id)->find()) {
                                                $valid_partition_ids[] = $id;
                                            }
                                        }
                                    }

                                    // 允许发帖
                                    $img = Request::post('img', '');

                                    $data = [
                                        'title' => Request::post('title'),
                                        'text' => $md_base,
                                        'img' => $img,
                                        'time' => time()
                                        // 不再更新post_partition字段，通过关联表管理
                                    ];

                                    Post::ChangePost($post_id, $data);

                                    // 更新分区关系
                                    if (!empty($valid_partition_ids)) {
                                        // 先删除旧的分区关系
                                        Db::table('site_post_partition_relation')->where('post_id', $post_id)->delete();

                                        // 添加新的分区关系
                                        foreach ($valid_partition_ids as $pid) {
                                            Db::table('site_post_partition_relation')->insert([
                                                'post_id' => $post_id,
                                                'partition_id' => $pid
                                            ]);
                                        }
                                    }

                                    $code = 200;
                                    $msg = '修改成功';
                                    return json(array('code' => $code, 'msg' => $msg, 'data' => $post_id));
                                } else {
                                    $code = 403;
                                    $msg = '字数过多';
                                }
                            } catch (Throwable $e) {
                                $code = 401;
                                $msg = '请求参数有误';
                            }
                        } else {
                            $code = 403;
                            $msg = '标题字数过多';
                        }
                    }
                    return json(array('code' => $code, 'msg' => $msg));
                } else {
                    //无权限
                    return json(array('code' => 403, 'msg' => '修改失败'));
                }
            }
        }
    }
}
